<template>
	<!-- 顶部筛选栏 -->
	<view class="filter-bar">
		<view class="filter-title">
			<picker mode="selector" @change="onstoreChange" :value="index" :range="storeArray">
				<view class="left">
					<text>全部店铺</text>
					<uni-icons type="down" color="#333333"></uni-icons>
				</view>
			</picker>
			<view class="right">
				<uni-icons type="search" color="#333333" size="26" style="margin-right: 20rpx;"
					@tap="goSearch"></uni-icons>
				<uni-icons type="more-filled" color="#333333" size="26"></uni-icons>
			</view>
		</view>
		<view class="filter-counts">
			<view class="count-item" v-for="(item, index) in countItems" :key="index" @click="selectItem(index)">
				<text :class="{'count-number': true, 'count-red': selectedIndex === index}">{{ item.count }}</text>
				<text
					:style="{ color: selectedIndex === index? '#000' : '#666666', fontSize: selectedIndex === index? '24rpx' : '23rpx' }">{{ item.statusDesc }}</text>
			</view>
		</view>
		<view class="filter-sort">
			<picker mode="selector" @change="onSortChange" :value="index" :range="array">
				<view class="sort-item">
					<text>{{sortTitle}}</text>
					<uni-icons type="down"></uni-icons>
				</view>
			</picker>
			<picker mode="selector" :value="timeIndex" :range="timeArray" @change="onFilterChange">
				<view class="sort-item">
					<text>{{timeTitle}}</text>
					<uni-icons type="down"></uni-icons>
				</view>
			</picker>
			<!-- <picker mode="selector" range="['全部']" @change="onFilterChange">
				<view class="sort-item">
					<text>全部</text>
					<uni-icons type="down"></uni-icons>
				</view>
			</picker> -->
		</view>
	</view>
	<scroll-view scroll-y class="scroll-content" @scrolltolower="loadMore" :refresher-enabled="true"
		:refresher-triggered="refreshing" @refresherrefresh="onRefresh" style="height: calc(100vh - 160px)">
		<!-- 订单详情 -->
		<view class="order-detail" v-for="(item, index) in orderList" :key="item.id" @tap="goOrderDetails(item.id)">
			<view class="order-header">
				<view style="display:flex;justify-content: flex-start;align-items: center;">
					<view class="left">
						{{item.id}}
					</view>
					<view class="right">
						<view class="order-time">
							<text class="time-text">预计{{item.expectEndTime}}
								<text style="color: #000;font-weight: 500;">前送达</text>
							</text>
						</view>
						<view class="order-number">
							<text v-if="item.orderType == 1">立即送达</text>
							<text v-if="item.orderType == 2">预约单</text>
							<text style="color: #3399ff;margin-left: 15rpx;">{{item.timeDifference}}<text
									style="color: #333;">前下单</text>
							</text>
						</view>
						<view class="order-shop">
							<uni-icons type="shop"></uni-icons>
							<text>{{item.shopName}}</text>
						</view>
					</view>
				</view>
				<uni-icons type="right"></uni-icons>
				<view class="orderStatus" v-if="item.orderStatus == 1">新订单</view>
				<view class="orderStatus" v-if="item.orderStatus == 2">待接单</view>
				<view class="orderStatus" v-if="item.orderStatus == 3">取货中</view>
				<view class="orderStatus" v-if="item.orderStatus == 4">配送中</view>
				<view class="orderStatus" v-if="item.orderStatus == 5">异常单</view>
				<view class="orderStatus" v-if="item.orderStatus == 6">退款单</view>
				<view class="orderStatus" v-if="item.orderStatus == 7">完成单</view>
				<view class="orderStatus" v-if="item.orderStatus == 8">取消单</view>
			</view>
			<view class="order-info">
				<view class="info-item">
					<text>{{item.receiverName}}</text>
				</view>
				<view class="info-item">
					<text>{{item.receiverPhone}}</text>
					<view class="icon-container" @tap.stop="callPhone(item.receiverPhone)">
						<uni-icons type="phone-filled" color="#4b6fff" size="20"></uni-icons>
					</view>
					<view class="icon-container"
						@tap.stop="openMap(item.receiverLatitude,item.receiverLongitude,item.receiverName,item.receiverAddress)">
						<uni-icons type="location-filled" color="#4b6fff" size="20"></uni-icons>
					</view>
				</view>
				<view class="info-item">
					<text>{{item.receiverAddress}}{{item.receiverAddressDetail}}</text>
				</view>
				<view class="info-item">
					<text>订单号:
						<text style="font-size: 25.36rpx;color: #999999;">{{item.orderId}}</text>
					</text>
					<button size="mini" type="default" plain @click.stop="copyOrderNumber(item.orderId)">复制</button>
				</view>
				<view class="info-item" v-for="(val,index) in item.product_list" :key="index"
					style="display: flex;flex-direction: column;align-items: flex-start;">
					<view class="">
						<text class="product-count">{{val.count}}件商品</text>
						<!-- <text class="product-price">单价：{{val.price / 100}}元</text> -->
					</view>
					<text style="color: #000;margin-top: 10rpx;font-size: 32rpx;">{{val.name}}</text>
				</view>
				<text class="product-price">商家实收：{{item.shopActualAmount / 100}}元</text>
			</view>
			<view class="order-note">
				<text>备注：{{item.orderRemark}}</text>
			</view>
			<view class="order-buttons">
				<button style="background: #f56c6c;color: #ffffff;" size="mini" @tap.stop="handleBtn(item.id,1)"
					v-if="item.orderStatus == 1">取消外卖单</button>
				<button style="background: #e6ebff;color: #5365ff;" size="mini" @tap.stop="handleBtn(item.id,2)"
					v-if="item.orderStatus == 2 || item.orderStatus == 3 || item.orderStatus == 4">取消配送</button>
				<button style="background: #5164ff;color: #ffffff;" size="mini" @tap.stop="handleBtn(item.id,3)"
					v-if="item.orderStatus == 1">配送下单</button>
				<button style="background: #eeeeee;color: #333333;" size="mini" @tap.stop="refundOrder(item.id)"
					v-if="item.orderStatus == 6">退款操作</button>
				<button style="background: #5164ff;color: #ffffff;" size="mini" @tap.stop="handleBtn(item.id,3)"
					v-if="item.orderStatus == 5">再次配送</button>
			</view>
		</view>
		<view class="empty" v-if="isEmpty">
			<image src="/static/empty-icon.png" mode="widthFix"></image>
			<text>暂无数据，如有问题，请联系客服</text>
		</view>
	</scroll-view>
	<uni-popup ref="refundPopup" type="center">
		<view class="modal-container">
			<view class="modal-header">
				<uni-icons type="help-filled" size="45" color="#FF9800"></uni-icons>
			</view>
			<view class="modal-body">
				<view class="modal-message">是否同意此订单的退款请求？</view>
			</view>
			<view class="modal-footer">
				<button @click="hideModal" class="btnw">拒绝退款</button>
				<button @click="confirmAction" class="btnb">同意退款</button>
			</view>
		</view>
	</uni-popup>
	<uni-popup ref="popup" type="top" @close="close">
		<view class="popup-content">
			<view class="popup-header">
				<text>请选择拒绝原因</text>
			</view>
			<view class="popup-body">
				<uni-data-select v-model="code" :localdata="range" @change="selecChange"></uni-data-select>
				<input type="text" v-model="remark" v-if="code == 103" placeholder="输入详细拒绝原因" />
			</view>
			<view class="popup-footer">
				<button @click="cancelProp" type="default" style="color: #666;">取消</button>
				<button @click="confimPopup" type="primary" :disabled="isDisabled"
					style="background: #2196f3;">确定</button>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import {
		getOrderList,
		cancelOrder,
		cancelDelivery,
		deliveryOrder,
		refundOrder,
		getOrderBill
	} from "@/api/orderApi/order.js"
	export default {
		data() {
			return {
				params: {
					page: 1,
					page_size: 5,
					orderStatus: 0,
					sortType: 1,
					expectStartTime: '',
					orderId: ''
				},
				orderList: [],
				isEmpty: false,
				array: ['全部订单', '今日发货'],
				storeArray: ['全部店铺'],
				index: 0,
				timeIndex: 0,
				timeArray: ['按下单时间倒序', '按下单时间正序'],
				countItems: [],
				selectedIndex: 0,
				totalCount: '',
				refreshing: false,
				code: '',
				remark: '',
				isDisabled: true,
				range: [{
						value: 101,
						text: "商家已出餐"
					},
					{
						value: 102,
						text: "骑手已在取货途中"
					},
					{
						value: 104,
						text: "商品已送出"
					},
					{
						value: 105,
						text: "已与用户达成一致"
					},
					{
						value: 106,
						text: "用户已收到商品"
					},
					{
						value: 107,
						text: "餐品已在制作中"
					},
					{
						value: 103,
						text: "其他原因"
					},
				],
				id: '',
				sortTitle: '全部订单',
				timeTitle: "按下单时间"
			}
		},
		watch: {
			code() {
				this.checkDisable();
			},
			remark() {
				this.checkDisable();
			}
		},
		methods: {
			onRefresh() {
				this.refreshing = true;
				this.params.page = 1
				this.params.orderId = ''
				this.getOrderList()
			},
			loadMore() {
				if (this.params.page * this.params.page_size >= this.totalCount) {
					return;
				}
				this.params.page++;
				this.params.orderId = '';
				this.getOrderList();
			},
			selectItem(index) {
				this.selectedIndex = index;
				this.params.orderStatus = index
				this.params.orderId = ''
				this.params.page = 1
				this.getOrderList()
			},
			onstoreChange(e) {
				// 模拟接口调用
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				setTimeout(() => {
					uni.hideLoading();
				}, 1000);
			},
			onSortChange(e) {
				if (e.detail.value == 0) {
					this.sortTitle = "全部订单"
					this.params.expectStartTime = ''
					this.params.page = 1
					this.getOrderList()

				} else if (e.detail.value == 1) {
					this.sortTitle = "今日发货"
					const currentDate = new Date();
					const year = currentDate.getFullYear();
					const month = String(currentDate.getMonth() + 1).padStart(2, '0');
					const day = String(currentDate.getDate()).padStart(2, '0');
					this.params.expectStartTime = `${year}-${month}-${day}`;
					this.params.page = 1
					this.getOrderList()
				}
			},
			onFilterChange(e) {
				if (e.detail.value == 0) {
					this.timeTitle = "按下单时间倒序"
					this.params.sortType = 1
					this.params.orderId = ''
					this.params.page = 1
					this.getOrderList()
				} else {
					this.timeTitle = "按下单时间正序"
					this.params.sortType = 2
					this.params.orderId = ''
					this.params.page = 1
					this.getOrderList()
				}
			},
			copyOrderNumber(value) {
				uni.setClipboardData({
					data: value,
					success: () => {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						});
					},
					fail: () => {
						uni.showToast({
							title: '复制失败',
							icon: 'none'
						});
					}
				});
			},
			callPhone(number) {
				uni.makePhoneCall({
					phoneNumber: number,
					success: (res) => {
						console.log(res);
					},
					fail: (err) => {
						console.log(err);
					}
				});
			},
			openMap(lat, lng, name, address) {
				console.log(lat, lng);
				uni.openLocation({
					latitude: Number(lat),
					longitude: Number(lng),
					name: name,
					address: address,
					success: (res) => {
						console.log(res);
					},
					fail: (err) => {
						console.log(err);
					}
				});
			},
			// 订单详情
			goOrderDetails(id) {
				uni.navigateTo({
					url: `/pagesOrder/orderDetail/orderDetail?id=${id}`
				})
			},
			//订单列表
			getOrderList() {
				getOrderList(this.params).then(res => {
					if (res.code == 200) {
						if (res.data.list.length > 0) {
							this.isEmpty = false
						} else {
							this.isEmpty = true
						}
						const formatDate = (timestamp) => {
							if (typeof timestamp === 'number' && timestamp > 0) {
								const date = new Date(timestamp);
								const year = date.getFullYear();
								const month = String(date.getMonth() + 1).padStart(2, '0');
								const day = String(date.getDate()).padStart(2, '0');
								const hours = String(date.getHours()).padStart(2, '0');
								const minutes = String(date.getMinutes()).padStart(2, '0');
								const seconds = String(date.getSeconds()).padStart(2, '0');
								return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
							}
							return 'Invalid Date';
						};

						const formatTimeDifference = (timestamp) => {
							if (typeof timestamp === 'number' && timestamp > 0) {
								const now = new Date().getTime();
								const diff = now - timestamp;

								const minutes = Math.floor(diff / (1000 * 60));
								const hours = Math.floor(diff / (1000 * 60 * 60));
								const days = Math.floor(diff / (1000 * 60 * 60 * 24));

								if (minutes < 60) {
									return `${minutes}分钟`;
								} else if (hours < 24) {
									return `${hours}小时`;
								} else {
									return `${days}天`;
								}
							}
							return 'Invalid Date';
						};
						res.data.group[0].count = '*'
						this.countItems = res.data.group
						res.data.list.forEach((val) => {
							val.expectEndTime = Number(val.expectEndTime);
							val.expectEndTime = formatDate(val.expectEndTime);
							val.orderCreateTime = Number(val.orderCreateTime);
							val.orderCreateTimeFormatted = formatDate(val.orderCreateTime);
							val.timeDifference = formatTimeDifference(val.orderCreateTime);
						});
						this.refreshing = false;
						this.totalCount = res.data.total
						if (this.params.page === 1) {
							this.orderList = res.data.list;
						} else {
							this.orderList = this.orderList.concat(res.data.list);
						}
					}
				})
			},
			goSearch() {
				uni.navigateTo({
					url: "/pagesOrder/searchOrder/searchOrder",
					animationType: 'pop-in',
					animationDuration: 200
				})
			},
			// 取消外卖单
			handleBtn(id, type) {
				let text = '';
				if (type === 1) {
					text = '确定取消此外卖单吗？';
				} else if (type === 2) {
					text = '确定取消此单配送吗？';
				} else if (type === 3) {
					getOrderBill({
						id
					}).then((priceRes) => {
						if (priceRes.code === 200) {
							const minPrice = priceRes.data.min_estimatePrice / 100;
							const maxPrice = priceRes.data.max_estimatePrice / 100;
							text = `预估配送价格${minPrice} - ${maxPrice}元，确定要配送此单吗？`;
							uni.showModal({
								title: "提示",
								content: text,
								success: (res) => {
									if (res.confirm) {
										deliveryOrder({
											id: id
										}).then((res) => {
											if (res.code === 200) {
												uni.showToast({
													icon: "none",
													title: "操作成功"
												});
												setTimeout(() => {
													this.params.orderId = '';
													this.params.page = 1;
													this.getOrderList();
												}, 1000);
											}
										});
									}
								}
							});
						} else {
							uni.showToast({
								icon: "none",
								title: "获取价格信息失败，请稍后重试"
							});
						}
					})
					return;
				}

				uni.showModal({
					title: "提示",
					content: text,
					success: (res) => {
						if (res.confirm) {
							if (type === 1) {
								cancelOrder({
									id: id
								}).then((res) => {
									if (res.code === 200) {
										uni.showToast({
											icon: "none",
											title: "操作成功"
										});
										setTimeout(() => {
											this.params.orderId = '';
											this.params.page = 1;
											this.getOrderList();
										}, 1000);
									}
								});
							} else if (type === 2) {
								cancelDelivery({
									id: id
								}).then((res) => {
									if (res.code === 200) {
										uni.showToast({
											icon: "none",
											title: "操作成功"
										});
										setTimeout(() => {
											this.params.orderId = '';
											this.params.page = 1;
											this.getOrderList();
										}, 1000);
									}
								});
							}
						}
					}
				});
			},
			selecChange(e) {
				this.code == e
			},
			checkDisable() {
				this.isDisabled = (this.code === '') || (this.code === 103 && this.remark === '');
			},
			// 退款
			refundOrder(id) {
				this.$refs.refundPopup.open()
				this.id = id
			},
			confirmAction() {
				refundOrder({
					id: this.id,
					agress: true
				}).then(res => {
					if (res.code == 200) {
						uni.showToast({
							icon: "none",
							title: "操作成功"
						})
						this.$refs.refundPopup.close()
						setTimeout(() => {
							this.params.orderId = ''
							this.params.page = 1
							this.getOrderList()
						}, 1000)
					}
				})
			},
			hideModal() {
				this.$refs.refundPopup.close();
				this.$refs.popup.open();
			},
			confimPopup() {
				this.$refs.refundPopup.close()
				refundOrder({
					id: this.id,
					agress: false,
					remark: this.remark,
					code: this.code
				}).then(res => {
					if (res.code == 200) {
						uni.showToast({
							icon: "none",
							title: "操作成功"
						})
						setTimeout(() => {
							this.params.orderId = ''
							this.params.page = 1
							this.getOrderList()
						}, 1000)
						this.remark = '';
						this.code = '';
						this.$refs.popup.close();
					}
				})
			},
			cancelProp() {
				this.remark = '';
				this.code = '';
				this.$refs.popup.close();
			}
		},
		onShow() {
			uni.$on('searchInputValue', (value) => {
				this.params.orderId = value;
			});
			this.getOrderList()
		}
	}
</script>
<style>
	page {
		background-color: #f5f5f5;
	}
</style>
<style lang="scss">
	.filter-bar {
		background-color: #fff;
		padding: 0rpx 20rpx 20rpx 20rpx;
		position: sticky;
		top: 0;
		z-index: 1;

		.filter-title {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.left {
				display: flex;
				align-items: center;

				text {
					font-size: 32rpx;
					color: #333333;
					font-weight: 600;
					margin-right: 10rpx;
				}
			}

			.right {
				display: flex;
				align-items: center;
			}

		}

		.filter-counts {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 40rpx;

			.count-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				margin-right: 20rpx;

				.count-number {
					width: 74rpx;
					height: 38rpx;
					border-radius: 19rpx 19rpx 19rpx 19rpx;
					font-size: 28rpx;
					font-weight: bold;
					margin-bottom: 15rpx;
					display: flex;
					justify-content: center;
					align-items: center;
				}

				.count-red {
					background: linear-gradient(90deg, #4876FF 0%, #5260FF 100%);
					color: #fff;
				}

				text {
					font-size: 26rpx;
				}

			}
		}



		.filter-sort {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 27rpx;

			.sort-item {
				padding: 7rpx 27rpx;
				background-color: #f5f7f6;
				border-radius: 26rpx;
				display: flex;
				justify-content: space-around;
				align-items: center;
				margin-right: 20rpx;

				text {
					font-size: 24rpx;
					margin-right: 10rpx;
				}

				.iconfont {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}

	.scroll-content {
		width: 95%;
		overflow-y: auto;
		padding: 20rpx;
		height: 100vh;
	}

	.order-detail {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-top: 20rpx;

		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			background: #f5f5f5;
			padding: 20rpx 10rpx;
			position: relative;

			.left {
				width: 58rpx;
				height: 58rpx;
				background: #E4E4EB;
				border-radius: 50%;
				margin-right: 24rpx;
				font-size: 25rpx;
				color: #333333;
				font-weight: bold;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.right {
				display: flex;
				flex-direction: column;
				align-items: flex-start;

				.order-time {
					font-size: 29rpx;
					color: #3399ff;
					font-weight: bold;
				}

				.order-number {
					display: flex;
					align-items: center;
					margin-top: 5rpx;

					.number-text {
						font-size: 29rpx;
						font-weight: bold;
						margin-right: 10rpx;
					}

					text {
						font-size: 24rpx;
					}
				}

				.order-shop {
					display: flex;
					align-items: center;
					margin-top: 10rpx;

					text {
						font-size: 25rpx;
						color: #666666;
					}
				}
			}

			.orderStatus {
				position: absolute;
				top: 0;
				right: 0;
				background-color: #f44336;
				color: #fff;
				padding: 5rpx 15rpx;
				border-radius: 0rpx 0rpx 0rpx 30rpx;
				font-size: 24rpx;
			}
		}

		.order-info {
			margin-bottom: 20rpx;

			.info-item {
				display: flex;
				align-items: center;
				font-size: 29rpx;
				color: #333333;
				margin-bottom: 10rpx;

				.icon-container {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					background-color: #e4e4eb;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-left: 20rpx;
				}
			}

			.product-count {
				font-weight: bold;
			}

			.product-price {
				color: red;
				margin-left: 10rpx;
			}
		}

		.order-note {
			font-size: 24rpx;
			color: #999;
			padding: 16rpx 14rpx;
			margin-bottom: 20rpx;
			background-color: #f5f5f5;
		}

		.order-buttons {
			display: flex;
			justify-content: space-between;
			margin-top: 20rpx;

			button {
				flex: 1;
				margin-right: 10rpx;
				height: 70rpx;
				text-align: center;
				line-height: 70rpx;

				&:last-child {
					margin-right: 0;
				}
			}
		}
	}

	.empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);

		image {
			width: 200rpx;
			margin-bottom: 20rpx;
		}

		text {
			font-size: 24rpx;
		}
	}

	.popup-content {
		background-color: #fff;
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.popup-header {
			text-align: center;
			font-size: 38rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20px;
			margin-top: 20rpx;
		}

		.popup-body {
			margin-bottom: 20rpx;

			input {
				padding: 10rpx;
				border: 1px solid #ccc;
				border-radius: 5rpx;
				margin-bottom: 10rpx;
				font-size: 28rpx;
				margin-top: 50rpx;
			}
		}

		.popup-footer {
			text-align: center;
			margin-top: 40rpx;
			display: flex;
			justify-content: space-around;
			align-items: center;

			button {
				width: 42%;
				height: 87rpx;
				font-size: 36rpx;
				border-radius: 40rpx;
			}
		}
	}

	.modal-container {
		width: 300px;
		background-color: #fff;
		border-radius: 10px;
		padding: 20px;
		text-align: center;

		.modal-header {
			margin-bottom: 20px;
		}

		.modal-title {
			font-size: 18px;
			font-weight: bold;
			margin-bottom: 10px;
		}

		.modal-message {
			font-size: 32rpx;
			color: #666;
			margin-bottom: 20px;
		}

		.modal-footer {
			display: flex;
			justify-content: space-around;

			.btnw {
				width: 46%;
				height: 94rpx;
				border-radius: 88rpx 88rpx 88rpx 88rpx;
				border: 2rpx solid rgba(153, 153, 153, 0.38);
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: 500;
				font-size: 34rpx;
				color: #666666;
			}

			.btnb {
				width: 46%;
				height: 94rpx;
				background: #2196f3;
				border-radius: 132rpx 132rpx 132rpx 132rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: 500;
				font-size: 34rpx;
				color: #FFFFFF;
			}
		}
	}
</style>